package cn.fl.mcr.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.user.facade.system.api.ISysUsrQueryApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.condition.SysUsrSysRQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.user.facade.system.dto.SysUsrSysRDTO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.system.transform.SysUsrSysRVOTransform;
import cn.fl.system.transform.SysUsrVOTransform;
import cn.fl.system.vo.SysUsrSysRVO;
import cn.fl.system.vo.SysUsrVO;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCstCreditRecQC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrCstCreditRecService;
import cn.fl.mcr.vo.McrCstCreditRecVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSONObject;

import fl.constant.facade.framework.constant.SystemConstant;

/**
 * @Description: 客户小贷授信记录 控制层
 */
@Controller
@RequestMapping("/mcr/mcrCstCreditRec")
public class McrCstCreditRecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrCstCreditRecController.class);

	/**
	 * McrCstCreditRec 服务层BEAN
	 */
	@Autowired
	private IMcrCstCreditRecService mcrCstCreditRecService;
	
	@Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISysUsrQueryApiService sysUsrQueryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrCstCreditRec/mcrCstCreditRecList");
		view.addObject("currentUserId", CurrentThreadContext.getCurrentUserId());
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCstCreditRec/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecQC qc) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		String creditTmStr = request.getParameter("creditTmStr");
		String claim = request.getParameter("claim");
		String operationStatus = request.getParameter("operationStatus");
		String currentUserId = request.getParameter("currentUserId");


		if(!StringUtils.isEmpty(creditTmStr)){
			qc.setCreditTm(DateUtils.formatStringToDate(creditTmStr, "yyyy-MM-dd"));
		}
		//qc.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
        SysUsrSysRQueryCondition condition = new SysUsrSysRQueryCondition();
        if(StringUtils.isNotEmpty(qc.getCertNo())){
            condition.setCertNo(qc.getCertNo());
        }
        if(StringUtils.isNotEmpty(qc.getUsrNm())){
            condition.setUsrNm(qc.getUsrNm());
        }
        if(StringUtils.isNotEmpty(qc.getUsrId())){
            condition.setUsrId(qc.getUsrId());
        }
		/*if(StringUtils.isNotEmpty(qc.getClaim())){
			qc.setClaim(null);
		}*/

		BaseLogUtils.info(logger,"initList","小贷信审列表.请求参数.claim:"+claim+",operationStatus:"+operationStatus);
		if(StringUtils.isNotEmpty(claim)){
			SysUsrSysRQueryCondition sysUsrSysRQueryCondition = new SysUsrSysRQueryCondition();
			sysUsrSysRQueryCondition.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
			sysUsrSysRQueryCondition.setUsrId(Long.parseLong(claim));
			sysUsrSysRQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
			BaseLogUtils.info(logger,"initList","小贷信审列表.查询领取人信息.claim:"+claim+",param:"+JSONObject.toJSONString(sysUsrSysRQueryCondition));
			List<SysUsrSysRDTO> sysUsrSysRDTOS = this.sysUsrQueryApiService.searchSysUsrSysRList(sysUsrSysRQueryCondition);
			BaseLogUtils.info(logger,"initList","小贷信审列表.查询领取人信息.返回结果.claim:"+claim+",param:"+JSONObject.toJSONString(sysUsrSysRDTOS));
			if (CollectionUtils.isNotEmpty(sysUsrSysRDTOS)){
				SysUsrSysRDTO sysUsrSysRDTO = sysUsrSysRDTOS.get(0);
				claim = sysUsrSysRDTO.getUsrNm();
			}else{
				claim = null;
			}
			qc.setClaim(claim);
		}

		if(StringUtils.isNotEmpty(operationStatus)){
			// 待领取
			if ("1".equals(operationStatus)){
				qc.setOperationStatus("1");
			}
			// 查看信审
			if ("2".equals(operationStatus)){
				qc.setOperationStatus("2");
			}
			// 添加信审
			if ("3".equals(operationStatus) && StringUtils.isNotEmpty(currentUserId)){
				qc.setClaim(currentUserId);
				qc.setOperationStatus("3");
			}
		}
		if(StringUtils.isEmpty(qc.getAuditVisitStatus())){
			qc.setAuditVisitStatus(null);
		}
        condition.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
        condition.setIsDel(BaseConstant.IS_YESNO_NO);
        if(StringUtils.isNotEmpty(qc.getCertNo()) || StringUtils.isNotEmpty(qc.getUsrNm()) || StringUtils.isNotEmpty(qc.getUsrId())){
			BaseLogUtils.info(logger, "initList", "查询数据完成.返回用户信息参数:" + JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
            List<SysUsrSysRVO> usrList = SysUsrSysRVOTransform.toVOList(sysUsrQueryApiService.searchSysUsrSysRList(condition));
			BaseLogUtils.info(logger, "initList", "查询数据完成.返回用户信息报文:" + JSONObject.toJSONString(usrList), CurrentThreadContext.getCurrentUserName());
			if(CollectionUtils.isNotEmpty(usrList)){
                qc.setUsrId(usrList.get(0).getUsrId());
            }else{
				return new ListPageVO<McrCstCreditRecVO>(null, page.getTotalCount());
			}
        }
        qc.setIsCredit((long) BaseConstant.IS_YESNO_YES);
		page.setCondition(qc);
		Pager pager = this.mcrCstCreditRecService.searchListPage(page);
		List<McrCstCreditRecVO> list = (List<McrCstCreditRecVO>) pager.getResultList();
		ListPageVO<McrCstCreditRecVO> listPage = new ListPageVO<McrCstCreditRecVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrCstCreditRecService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrCstCreditRecVO vo = this.mcrCstCreditRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCstCreditRec/mcrCstCreditRecAdd");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子详情页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCstCreditRec/mcrCstCreditRecDetail");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子详情页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do")
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			if(entity == null || entity.getCarId() == null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("新增失败，车辆ID不能为空");
				return result;
			}
			String creditTmStr = request.getParameter("creditTmStr");
			if(!StringUtils.isEmpty(creditTmStr)){
				entity.setCreditTm(DateUtils.formatStringToDate(creditTmStr, "yyyy-MM-dd"));
			}
			Long id = this.mcrCstCreditRecService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "更新数据 DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "更新数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "更新数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do")
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		try {
			if(entity == null || entity.getCarId() == null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败，车辆ID不能为空");
				return result;
			}
			String creditTmStr = request.getParameter("creditTmStr");
			if(!StringUtils.isEmpty(creditTmStr)){
				entity.setCreditTm(DateUtils.formatStringToDate(creditTmStr, "yyyy-MM-dd"));
			}
			entity.setMdfTm(new Date());
			boolean success = this.mcrCstCreditRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[carId="+entity.getCarId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[carId="+entity.getCarId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[carId="+entity.getCarId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[carId="+entity.getCarId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 作废记录
	 */
	@RequestMapping(value = "/cancel.do")
	@ResponseBody
	public Object cancel(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			if(entity == null || entity.getId() == null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("作废失败，ID不能为空");
				return result;
			}
			boolean success = this.mcrCstCreditRecService.cancel(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "作废成功.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "作废失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 领取记录
	 */
	@RequestMapping(value = "/claim.do")
	@ResponseBody
	public Object claim(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			if(entity == null || entity.getId() == null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("领取记录失败，ID不能为空");
				return result;
			}
			entity.setClaim(CurrentThreadContext.getCurrentUserId().toString());
			boolean success = this.mcrCstCreditRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "领取记录失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "领取记录成功.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "领取记录失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "领取记录失败.[ID="+entity.getId()+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 查询授信记录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryCreditList.do")
	@ResponseBody
	public Object queryCreditList(HttpServletRequest request, HttpServletResponse response, McrCstCreditRecQC qc) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			List<McrCstCreditRecVO> list = this.mcrCstCreditRecService.searchList(qc);
			if(list !=null && list.size()>0){
				result.setData(JSONObject.toJSONString(list));
				result.setInfo("查询授信记录成功");
			}else{
				result.setInfo("查询授信记录为空");
			}
			BaseLogUtils.info(logger, "queryCreditList", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "查询失败.[McrCstCreditRecQC="+qc+"] DATA:" + JSONObject.toJSONString(qc) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	@RequestMapping(value = "/test.do")
	@ResponseBody
	public Object queryCreditList(HttpServletRequest request, HttpServletResponse response) {
		DataResultDTO dto = mcrCstCreditRecService.test();
		return dto;
	}
	
	
}

